<template>
  <div class="app-container">
    <!-- 搜索--------------------------------- -->
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>{{ $t("common.filterSearch") }}</span>
        <el-button
          icon="el-icon-search"
          style="float: right"
          @click="fetchData()"
          type="primary"
          size="small"
        >
          {{ $t("common.search") }}
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" size="small" label-width="140px">
          <el-form-item :label="$t('courselist.search.id')">
            <el-input
              style="width: 203px"
              v-model="searchObj.course_id"
              :placeholder="$t('courselist.search.plid')"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('courselist.search.name')">
            <el-input
              style="width: 230px margin-left"
              v-model="searchObj.name"
              :placeholder="$t('courselist.search.plname')"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('courselist.search.type')">
            <el-input
              style="width: 203px margin-left"
              v-model="searchObj.type"
              :placeholder="$t('courselist.search.pltype')"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- --------------------------------- -->
    <!--导入按钮 -->
    <el-button type="primary" @click="importData">
      <i class="fa fa-plus" />{{ $t("common.import") }}
    </el-button>
    <!-- 导出按钮 -->
    <!-- <a href="http://42.194.159.131:8080/course/exportData" target="_blank" >
      <el-button type="text" @click="exportData"
        ><i class="fa fa-plus" /> {{ $t('common.export') }}</el-button
      >
    </a> -->
    <el-button @click="exportData" type="primary" plain>{{
      $t("common.export")
    }}</el-button>
    <!-- 添加-------------------------------- -->
    <div align="right">
      <el-button type="success" @click="addCourse">{{
        $t("common.add")
      }}</el-button>
    </div>
    <!-- 批量删除 -->
    <div>
      <el-button type="danger" size="mini" @click="removeRows()">{{
        $t("common.bulkDelete")
      }}</el-button>
    </div>
    <!-- --------------------------------------列表页 -->
    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        :label="$t('courselist.table.course_id')"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.course_id }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('courselist.table.teacher_id')"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.teacher_id }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('courselist.table.name')" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('courselist.table.cover_picture')"
        width="160"
        align="center"
      >
        <template slot-scope="{ row, $index }">
          <img
            :src="row.cover_picture"
            alt=""
            style="width: 130px; height: 100px"
          />
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('courselist.table.coursePartList')"
        align="center"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.coursePartList">
            <el-button
              type="success"
              plain
              @click="playVideo(scope.row.course_id)"
              ref="btn"
              size="mini"
            >
              查看视频播放
            </el-button>
          </div>
          <div v-else>暂无视频</div>
        </template>
      </el-table-column>

      <el-table-column :label="$t('courselist.table.type')" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('courselist.table.label')"
        align="center"
        width="160"
      >
        <template slot-scope="scope">
          <el-tag size="medium">{{ scope.row.label }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column :label="$t('courselist.table.price')" align="center">
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('courselist.table.brief_introduction')"
        align="center"
      >
        <template slot-scope="scope">
          <span
            style="
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
              display: block;
            "
          >
            {{ scope.row.brief_introduction }}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('common.operate')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="editCourse(scope.row.course_id)"
          >
            {{ $t("common.update") }}
          </el-button>

          <el-button
            size="mini"
            type="danger"
            @click="delCourse(scope.row.course_id)"
          >
            {{ $t("common.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">
      <el-form label-position="right" label-width="170px">
        <el-form-item label="文件">
          <el-upload
            :action="'http://42.194.159.131:8080/course/batchAddCourse'"
            :headers="headers"
            :on-success="onUploadSuccess"
            :multiple="false"
            class="upload-demo"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传excel文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- -------------------------------------- -->
    <!-- ----------------------------------分页 -->
    <div class="block" style="float: right; margin-top: 20px">
      <!--  <span class="demonstration">显示总数</span> -->
      <el-pagination
        background
        @current-change="fetchData"
        :current-page.sync="page_num"
        :page-size="page_size"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- --------------------------------------- -->
  </div>
</template>
<script>
import axios from "axios";
// import Http from "@/http/index"
import healcourse from "@/api/healthycourse";
import { getToken } from "@/utils/auth";
export default {
  //定义变量和初始值
  data() {
    return {
      list: [], //每页数据集合
      page_num: 1,
      page_size: 8, //每8个数据一页
      total: 1, //初始化
      searchObj: {}, //条件封装对象
      multipleSelection: [], //批量选择中选择的记录列表
      dialogImportVisible: false, //弹框
      headers: {
        Authorization: getToken(),
      },
    };
  },
  //在页面渲染前执行
  //调用methods定义的方法，得到数据
  created() {
    this.fetchData();
  },
  methods: {
    //导入数据字典
    importData() {
      this.dialogImportVisible = true;
    },
    //导出数据字典
    exportData() {
      this.btnLoading = true;
      healcourse
        .importcourse()
        .then((res) => {
          this.btnLoading = false;
          if (res.data.type) {
            // 文件下载
            const blob = new Blob([res.data], {
              type: "application/vnd.ms-excel",
            });
            let link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.setAttribute("download", "健康课程.xlsx");
            link.click();
            link = null;
            // this.$message.success('导出成功');
          } else {
            // 返回json
            this.$message.warning(res.data.msg);
          }
        })
        .catch((err) => {
          this.btnLoading = false;
          this.$message.error("下载失败");
        });
      // axios({
      //   method: "GET",
      //   url: "/course/exportData",
      //   responseType: "blob",
      //   headers: {
      //     Authorization: getToken(),
      //   },
      // })
      //   //  healcourse.importcourse()
      //   .then((res) => {
      //     //   console.log('aaaaaaa');

      //     this.btnLoading = false;
      //     if (res.data.type) {
      //       // 文件下载
      //       const blob = new Blob([res.data], {
      //         type: "application/vnd.ms-excel",
      //       });
      //       let link = document.createElement("a");
      //       link.href = URL.createObjectURL(blob);
      //       link.setAttribute("download", "健康课程.xlsx");
      //       link.click();
      //       link = null;
      //       // this.$message.success('导出成功');
      //     } else {
      //       // 返回json
      //       this.$message.warning(res.data.msg);
      //     }
      //   })
      //   .catch((err) => {
      //     this.btnLoading = false;
      //     this.$message.error("下载失败");
      //   });
    },
    //上传成功调用
    onUploadSuccess() {
      this.dialogImportVisible = false;
      this.fetchData(1);
      this.$message({
        message: "导入数据成功!",
        type: "success",
      });
    },
    //获取选择复选框的id值
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    //批量删除
    removeRows() {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //遍历数组得到每个id值，设置到idList里面
          var idList = [];
          for (var i = 0; i < this.multipleSelection.length; i++) {
            var obj = this.multipleSelection[i];
            var id = obj.course_id;
            idList.push(id);
          }
          //调用接口
          healcourse
            .batchRemoveCourse(idList)
            .then((resp) => {
              //提示
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //刷新页面数据
              this.fetchData(1);
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "删除失败!权限不足，请联系管理员进行升级",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //添加课程
    addCourse() {
      this.$router.push("/HealthyCourse/addcourse");
    },
    //编辑课程
    editCourse(course_id) {
      this.$router.push("/HealthyCourse/editcourse/" + course_id);
    },
    //查看视频详情
    playVideo(course_id) {
      this.$router.push("/HealthyCourse/detailvideo/" + course_id);
    },
    //页面列表页渲染，请求接口调用
    fetchData(page = 1) {
      this.page_num = page;
      var vm = this;
      healcourse
        .getHealthycourseList(this.page_num, this.page_size, this.searchObj)
        //请求成功调用
        .then((resp) => {
          vm.list = resp.data.Course.list;
          vm.total = resp.data.Course.total;
          if (
            this.searchObj.course_id == this.list[0].course_id ||
            this.searchObj.type == this.list[0].type
          ) {
            this.$message({
              type: "success",
              message: "搜索成功!",
            });
          }
        })
        .catch((error) => {});
    },
    // ------------------------------------------------
    // 删除方法------------------
    delCourse(course_id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用接口
          healcourse
            .delcourse(course_id)
            .then((resp) => {
              //提示
              console.log(resp);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //刷新页面数据
              this.fetchData(1);
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "删除失败!权限不足，请联系管理员进行升级",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          console.log("1231");
        });
    },
  },
};
</script>
